<script setup lang="ts">
  import { useAddressForm, useGetAddressDetail } from '../../services/useAddressList'
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import { computed, ref, watch } from 'vue'
  import { verifyPhone } from '@/utils/validate'
  import { FormInstance } from 'element-plus'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const { form, formSaveLoading, formSave, resetForm } = useAddressForm()
  const { detail, getDetailLoading, getDetail } = useGetAddressDetail()

  const props = defineProps({
    addressId: {
      type: String,
      default: () => '',
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 用于给地址选择组件回显
  const address = computed(() => {
    return {
      province: form.value.province,
      city: form.value.city,
      area: form.value.area,
      town: '',
    }
  })

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  // 表单校验规则
  const rules = {
    username: [{ required: true, message: '请输入收货人名称', trigger: ['change', 'blur'] }],
    phone: [
      { required: true, message: '请输入手机号', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          if (!verifyPhone(form.value.phone)) {
            callback(new Error('手机号码格式不正确'))
            return
          }
          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
    province: [
      { required: true, message: '请选择地址', trigger: ['change', 'blur'] },
      {
        validator: (rule, value, callback) => {
          const { province, city, area } = form.value
          if (!province || !city || !area) {
            callback(new Error('请选择地址'))
            return
          }
          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
    address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
  }

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    visible.value = false
    resetForm()
  }

  /**
   * 地址选择事件
   * @param addr - 选择的地址
   */
  const handleAddressChange = (addr: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    form.value.province = addr.province
    form.value.city = addr.city
    form.value.area = addr.area
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    if (props.addressId && !form.value.defaultAddr) {
      HMessageBox.error('不可以设置为否，因为必须有一个地址为默认地址')
      return
    }

    if (formInstance.value) {
      try {
        await formInstance.value.validate()
        const res = await formSave()
        if (res.code === 20000) {
          hideDialog()
          HMessage.success('保存成功')
          emits('update')
          resetForm()
          return
        }

        if (res.code === 400301) {
          HMessageBox.error('手机号重复')
          return
        }

        HMessageBox.error(res.message)
      } catch (e) {
        // error
      }
    }
  }

  /**
   * 手机号输入事件
   * @param phone - 手机号
   */
  const handlePhoneInput = (phone: string) => {
    form.value.phone = phone.replace(/[^\d]/g, '')
  }

  watch(visible, (value) => {
    if (value && props.addressId) {
      getDetail(props.addressId).then(() => {
        form.value = detail.value
      })
    }
  })
</script>

<template>
  <h-dialog
    v-model="visible"
    :title="props.addressId ? '修改地址' : '添加地址'"
    :loading="formSaveLoading || getDetailLoading"
    @close="hideDialog"
  >
    <el-form
      ref="formInstance"
      :model="form"
      label-position="top"
      inline-message
      class="modal_form_content"
      :rules="rules"
    >
      <el-form-item label="收货人名称" prop="username">
        <el-input v-model.trim="form.username" placeholder="请输入收货人名称" maxlength="50" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model.trim="form.phone"
          placeholder="请输入手机号"
          maxlength="11"
          @input="handlePhoneInput"
        />
      </el-form-item>

      <el-form-item label="地址" prop="province">
        <single-address :address="address" @change="handleAddressChange" />
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model.trim="form.address"
          type="textarea"
          maxlength="200"
          show-word-limit
          placeholder="请输入详细地址"
          class="detail-address"
        />
      </el-form-item>

      <div class="same_line">
        <el-form-item label="状态" prop="status" class="same_line">
          <el-radio-group v-model="form.status">
            <el-radio :value="false" size="small">显示</el-radio>
            <el-radio :value="true" size="small">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否为默认地址" prop="defaultAddr" class="same_line">
          <el-radio-group v-model="form.defaultAddr">
            <el-radio :value="true" size="small">是</el-radio>
            <el-radio :value="false" size="small">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <h-button type="primary" is-modal @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss">
  .detail-address {
    :deep(.el-textarea__inner) {
      width: 100% !important;
      height: 120px !important;
    }
  }
</style>
